const { db, query } = require("../db")

const SA = require('../utils/StrAndArr')

// 登录
exports.login = (req, res, next) => {
  // console.log(req.body)
  const { username, password } = req.body
  const sql = `select * 
               from tb_users
               where username='${username}' and password='${password}';`
  db.query(sql, function (err, results) {
    if (err || results.length <= 0) {
      // console.log('登陆失败')
      return res.cc({ msg: '账号或密码错误' })
    }
    let userInfo = results[0]
    userInfo.password = ''
    res.cc({
      msg: '登陆成功',
      userInfo
    }, 200)
  })
}

// 获取用户信息
exports.getuserinfo = (req, res, next) => {
  const { username } = req.body
  const sql = `select * 
               from tb_users
               where username='${username}';`
  db.query(sql, function (err, results) {
    if (err || results.length <= 0) return res.cc({ msg: '无此用户' })
    res.cc({
      msg: '登陆成功',
      userInfo: results[0]
    }, 200)
  })
}

// 注册
exports.register = (req, res, next) => {
  const { username, password, bind } = req.body
  const usersql = `select * from tb_users where username='${username}' or bind='${bind}';`
  db.query(usersql, function (err, results) {
    if (results.length > 0) {
      return res.cc({ msg: '账号或绑定已存在' })
    } else {
      const sql = `insert into tb_users (username, password, name, bind, imgurl) values('${username}', '${password}', '${username}', '${bind}', '');`
      db.query(sql, function (err, result) {
        if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
        res.cc({ msg: '注册成功' }, 200)
      })
    }
  })
}

// 修改用户名
exports.setname = (req, res, next) => {
  const { username, name } = req.body
  const usersql = `select * 
               from tb_users
               where name='${name}';`
  db.query(usersql, function (err, results) {
    if (results.length > 0) {
      return res.cc({ msg: '用户名已存在' })
    } else {
      const sql = `update tb_users set name='${name}' where username='${username}';`
      db.query(sql, function (err, result) {
        if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
        res.cc({ msg: '修改成功' }, 200)
      })
    }
  })
}

// 修改绑定
exports.setbind = (req, res, next) => {
  const { username, bind } = req.body
  const usersql = `select * 
               from tb_users
               where name='${bind}';`
  db.query(usersql, function (err, results) {
    if (results.length > 0) {
      return res.cc({ msg: '该电话号/QQ已被绑定' })
    } else {
      const sql = `update tb_users set bind='${bind}' where username='${username}';`
      db.query(sql, function (err, result) {
        if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
        res.cc({ msg: '修改成功' }, 200)
      })
    }
  })
}

// 修改头像
exports.setimgurl = (req, res, next) => {
  const { username, imgurl } = req.body
  const sql = `update tb_users set imgurl='${imgurl}' where username='${username}';`
  db.query(sql, function (err, result) {
    if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
    res.cc({ msg: '修改成功' }, 200)
  })
}

// 修改密码
exports.setpassword = (req, res, next) => {
  const { username, oldpassword, newpassword } = req.body
  // console.log(req.body)
  // 忘记密码的新设密码
  if (oldpassword == null) {
    // console.log("111")
    const sql = `update tb_users set password='${newpassword}' where username='${username}';`
    db.query(sql, function (err, result) {
      if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
      res.cc({ msg: '修改成功' }, 200)
    })
  } else {
    // console.log("222")
    // 普通修改密码
    const usersql = `select * 
                      from tb_users
                      where username='${username}' and password='${oldpassword}';`
    // console.log(usersql)
    db.query(usersql, function (err, results) {
      if (results.length <= 0) {
        return res.cc({ msg: '用户不存在或旧密码错误' })
      } else {
        const sql = `update tb_users set password='${newpassword}' where username='${username}';`
        db.query(sql, function (err, result) {
          if (err) return res.cc({ msg: '[Database error]: ' + err.sqlMessage })
          res.cc({ msg: '修改成功' }, 200)
        })
      }
    })
  }
}

// 忘记密码
exports.forgetpassword = (req, res, next) => {
  const { username, bind } = req.body
  const usersql = `select * 
               from tb_users
               where username='${username}' and bind='${bind}';`
  // console.log(usersql)
  db.query(usersql, function (err, results) {
    if (results.length <= 0) {
      return res.cc({ msg: '输入绑定的手机号/QQ错误' })
    } else {
      res.cc({ msg: '查找成功' }, 200)
    }
  })
}

// 获取用户列表
exports.getuserlist= (req, res, next) => {
  const { query} = req.query
  // console.log(req.query)
  const sql = `select * 
               from tb_users;`
  db.query(sql, function (err, results) {
    // if (err || results.length <= 0) return res.cc({ msg: '无用户' })
    let list = []
    for (let i=0; i<results.length; i++) {
      if (results[i].username.indexOf(query) !== -1 || results[i].password.indexOf(query) !== -1 || results[i].name.indexOf(query) !== -1 || results[i].bind.indexOf(query) !== -1) {
        list.push(results[i])
      }
    }
    res.cc({
      msg: '查找成功',
      userlist: list
    }, 200)
  })
}

// 添加/修改用户
exports.setuserinfo = async (req, res, next) => {
  const { username, name, password, bind, imgurl, isAdd } = req.body

  if (!isAdd) {
    // 修改用户信息
    let list = await query(`select * from tb_users where username!='${username}';`)
    for (let i=0; i<list.length; i++) {
      if (list[i].name == name) {
        return res.cc({
          msg: '昵称已存在'
        })
      } else if (list[i].bind == bind) {
        return res.cc({
          msg: '手机/QQ已被绑定'
        })
      }
    }
    await query(`update tb_users set name='${name}', password='${password}', bind='${bind}', imgurl='${imgurl}' where username='${username}';`)
    return res.cc({
      msg: '修改成功'
    }, 200)
  } else {
    // 新添用户信息
    let userlist = await query(`select * from tb_users where username='${username}';`)
    if (userlist.length !== 0) {
      return res.cc({
        msg: '账户已存在'
      })
    } 
    let namelist = await query(`select * from tb_users where name='${name}';`)
    if (namelist.length !== 0) {
      return res.cc({
        msg: '昵称已存在'
      })
    } 
    let bindlist = await query(`select * from tb_users where bind='${bind}';`)
    if (bindlist.length !== 0) {
      return res.cc({
        msg: '手机/QQ已被绑定'
      })
    }
    await query(`insert into tb_users (username, password, name, bind, imgurl) values('${username}', '${password}', '${name}', '${bind}', '${imgurl}');`)
    return res.cc({
      msg: '添加成功'
    }, 200)
  }
}

// 删除用户
exports.deluserinfo = async (req, res, next) => {
  const { username } = req.body
  let userlist = await query(`select * from tb_users where username='${username}';`)
  if (userlist.length !== 0 ) {
    // 删除用户信息
    await query(`delete from tb_users where username='${username}';`)
    res.cc({
      msg: '删除成功'
    }, 200)
  } else {
    res.cc({
      msg: '无此用户'
    })
  }
}


// 获取做题记录
// exports.getrecords = (req, res, next) => {
//   const { username } = req.body
//   const sql = `select *
//                from tb_records
//                where username='${username}';`
//   db.query(sql, function (err, results) {
//     if (err || results.length <= 0) return res.cc({ msg: '无做题记录' }, 401)
//     for (let i = 0; i < results.length; i++) {
//       results[i].questionIds = SA.StrToArr(results[i].questionIds)
//       results[i].answers = SA.StrToArr(results[i].answers)
//     }
//     res.cc({
//       msg: '获取成功',
//       results
//     }, 200)
//   })
// }